//---------------------------------------------------------------------
// File: EventLogSaveStep.cs
// 
// Summary: 
//
//---------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, WHETHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
// PURPOSE.
//---------------------------------------------------------------------

namespace Microsoft.Services.BizTalkApplicationFramework.BizUnit
{
    using System;
    using System.Xml;
    using System.Management;

    /// <summary>
    /// The EventLogSaveStep test step clears the event log. Note: caution should be taken when clearing event log.
    /// </summary>
    /// 
    /// <remarks>
    /// The following shows an example of the Xml representation of this test step.
    /// 
    /// <code escaped="true">
    /// <TestStep assemblyPath="" typeName="Microsoft.Services.BizTalkApplicationFramework.BizUnit.EventLogSaveStep">
    ///		<Server>UKBTSTEST01</Server>
    ///		<DestinationPath>C:\MyLogs\ApplicationLog.evt</DestinationPath>
    /// </TestStep>
    ///	</code>
    ///	
    ///	<list type="table">
    ///		<listheader>
    ///			<term>Tag</term>
    ///			<description>Description</description>
    ///		</listheader>
    ///		<item>
    ///			<term>Server</term>
    ///			<description>The name of the machine where the event log should be saved from</description>
    ///		</item>
    ///		<item>
    ///			<term>DestinationPath</term>
    ///			<description>The local path to save the event log to</description>
    ///		</item>
    ///	</list>
    ///	</remarks>	

    public class EventLogSaveStep : ITestStep
    {
        /// <summary>
        /// ITestStep.Execute() implementation
        /// </summary>
        /// <param name='testConfig'>The Xml fragment containing the configuration for this test step</param>
        /// <param name='context'>The context for the test, this holds state that is passed beteen tests</param>
        public void Execute(XmlNode testConfig, Context context)
        {
            string destinationPath = context.ReadConfigAsString(testConfig, "DestinationPath");
            string server = context.ReadConfigAsString(testConfig, "Server");

            context.LogInfo("About to save the event on server: {0} to the following directory: {1}", server, destinationPath);
            
            ManagementScope Scope;

            if ((server.ToUpper() != Environment.MachineName.ToUpper()))
            {
                ConnectionOptions options = new ConnectionOptions();
                options.Impersonation = ImpersonationLevel.Impersonate;
                Scope = new ManagementScope(string.Format(@"\\{0}\root\cimv2", server), options);
            }
            else
            {
                ConnectionOptions options = new ConnectionOptions();
                options.Impersonation = ImpersonationLevel.Impersonate;
                Scope = new ManagementScope(@"root\cimv2", options);
            }

            SelectQuery query = new SelectQuery("Select * from Win32_NTEventLogFile");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(Scope, query);

            foreach (ManagementBaseObject logFileObject in searcher.Get())
            {
                object[] methodArgs = new object[] { destinationPath };

                try
                {
                    ((ManagementObject)logFileObject).InvokeMethod("BackupEventLog", methodArgs);
                }
                catch (Exception e1)
                {
                    //access denied on method call if scope path referes to the same  
                    context.LogException(e1);

                    throw;
                }
            }
        }
    }
}

